/**
 *  Copyright(C) 2012-2013 Suntec(Shanghai) Software Co., Ltd.
 *  All Right Reserved.
 */
package com.cugbmao.lucene;

import junit.framework.TestCase;

import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

/**
 * Descriptions
 * 
 * @version 2013年5月31日
 * @author Suntec
 * @since JDK1.6
 * 
 */
public class WildcardQueryTest extends TestCase {
	private Directory dir;
	private IndexReader reader;

	/*
	 * (non-Javadoc)
	 * @see junit.framework.TestCase#setUp()
	 */
	@Override
	protected void setUp() throws Exception {
		dir = new RAMDirectory();
		indexSingleFieldDocs( new Field[] { new TextField( "contents", "wild", Field.Store.YES ),
				new TextField( "contents", "child", Field.Store.YES ),
				new TextField( "contents", "mild", Field.Store.YES ),
				new TextField( "contents", "mildew", Field.Store.YES ) } );

		reader = DirectoryReader.open( dir );
	}

	private void indexSingleFieldDocs( Field[] fields ) throws Exception {
		IndexWriterConfig iwf = new IndexWriterConfig( Version.LUCENE_43, new WhitespaceAnalyzer( Version.LUCENE_43 ) );
		IndexWriter writer = new IndexWriter( dir, iwf );
		for ( int i = 0; i < fields.length; i++ ) {
			Document doc = new Document();
			doc.add( fields[i] );
			writer.addDocument( doc );
		}
// writer.forceMerge( 0 );
		writer.commit();
		writer.close();
	}

	public void testWildcard() throws Exception {

		IndexSearcher searcher = new IndexSearcher( reader );
		Query query = new WildcardQuery( new Term( "contents", "?ild*" ) ); // #A
		TopDocs matches = searcher.search( query, 10 );
		assertEquals( "child no match", 3, matches.totalHits );
		assertEquals( "score the same", matches.scoreDocs[0].score, matches.scoreDocs[1].score, 0.0 );
		assertEquals( "score the same", matches.scoreDocs[1].score, matches.scoreDocs[2].score, 0.0 );
	}
}
